import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import { Message } from 'element-ui'

const whiteList = ['/login', '/', '/404', '/mobile/company', '/preview'] // 不重定向白名单
NProgress.configure({
  showSpinner: false,
})
router.beforeEach((to, from, next) => {
  NProgress.start()
  //const hasToken = getToken()
  const hasToken = sessionStorage.getItem('token')
  if (hasToken) {
    if (to.path === '/login') {
      next({
        path: '/',
      })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      const hasMenu = store.state.menu && store.state.menu.length > 0
      //console.log(hasMenu)
      if (hasMenu) {
        if (to.meta.menuNo) {
          let oParams = { parentId: to.meta.menuNo }
          // if (to.matched.length > 2) {
          //   oParams.parentId = to.meta.parentId
          // }
          store.dispatch('getPagePermission', oParams).then((res) => {
            next()
          })
        } else {
          next()
        }
      } else {
        try {
          store.dispatch('getMenu').then((list) => {
            // store.dispatch('generateRoutes', list).then((res) => {
            //   //router.addRoutes(res)
            //   next({ ...to, replace: true })
            // })
            //console.log(list);
            //console.log(to)
            next({ ...to, replace: true })
          })
        } catch {
          store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    //console.log(to.path);
    //console.log(whiteList.indexOf(to.path) !== -1);
    //return false;
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
